#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Functions that are helpful to the Layer UX handlers.

TODO (jasonstredwick): Refactor models so search doesn't have to touch each
kind separately.  Probably use a PolyModel for this.
"""

__author__ = 'jasonstredwick@google.com (Jason Stredwick)'


import os

# Disable 'Import not at top of file' lint error.
# pylint: disable-msg=C6204
try:
  import auto_import_fixer
except ImportError:
  pass  # This will fail on unittest, ok to pass.

from layer.models.layer_simple import Simple
from layer.models.layer_static import Static

# Disable 'Import not at top of file' lint error.
# pylint: disable-msg=C6204
try:
  from google.appengine.ext.webapp import template
except ImportError:
  # For unit testing.
  from google.appengine.ext.webapp import template


def RenderTemplate(name, template_args=None, path='../templates'):
  """Renders the specified django template.

  *Note: This function was taken from bite/server/hud/handlers/base.py.
  Eventually, base.py will be broken out into common code and utilized by
  the Layer UX.

  If path is not specified, the we assume the hander and templates are in
  different folders:
    - root
      - handlers
      - templates
  Args:
    name: Str name of the file template.
    template_args: Dict argument passed to the template.
    path: Str relative path to the template.

  Returns:
    A string containing the render html template ready to be sent as a
    response.
  """
  template_args = template_args or {}
  path = os.path.join(os.path.dirname(__file__), path, name)
  return template.render(path, template_args)


def GetAllSortedLayers():
  """Returns a list of layers in order.

  This function has to get all layers for each kind and add them to
  a "global" list.  The list is then sorted based on layer id.

  Returns:
    A sorted list of layers.
  """
  layers = []

  query = Simple.all()
  # TODO(jasonstredwick): Change this to a cursor and select all.
  [layers.append(layer) for layer in query]
  query = Static.all()
  # TODO(jasonstredwick): Change this to a cursor and select all.
  [layers.append(layer) for layer in query]

  def __GetId(layer):
    return layer.id
  # Since the layer list is a composite of two queries, I am sorting them
  # based on their id.  The id is not a key, the id is a unique integer
  # assigned to every layer to manage layer order.
  layers.sort(key=__GetId)

  return layers


def FindLayer(url):
  """Find a single layer based on a url.

  Look through list of layers for all kinds for the given url.

  Args:
    url: Uses the url to find a specific layer.

  Returns:
    A layer or None.
  """
  if url:
    query = Simple.all()
    query.filter('url = ', url)
    # There is exactly one url for every layer; the url is the path to a
    # layer's manifest "file".
    layer = query.get()
    if layer:
      return layer

    query = Static.all()
    query.filter('url = ', url)
    layer = query.get()
    if layer:
      return layer

  return None

